<template>
  <div class="data-table-container layout-padding">
    <el-card class="layout-padding-auto" shadow="hover">
      <el-form ref="queryFormRef" :model="state.tableData.param.params" inline>
        <el-form-item class="!mr-4" prop="couponName">
          <el-input v-model="state.tableData.param.params.couponName" class="max-w-180px" clearable
                    placeholder="请输入券名称"
                    size="default">
          </el-input>
        </el-form-item>
        <el-form-item prop="couponType" style="width: 11%;">
          <el-select v-model="state.tableData.param.params.couponType" class="max-w-180px" clearable
                     placeholder="请选择券类型"
                     size="default">
            <el-option
                v-for="item in state.typeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-auth="'user.list'" class="!mr-4">
          <el-button size="default" type="primary" @click="getTableData">
            <el-icon>
              <ele-Search/>
            </el-icon>
            查询
          </el-button>
        </el-form-item>
        <el-form-item v-auth="'user.add'" class="!mr-4">
          <el-button size="default" type="success" @click="onOpenAddUser('add')">
            <el-icon>
              <ele-FolderAdd/>
            </el-icon>
            新增
          </el-button>
        </el-form-item>
        <el-form-item v-auth="'user.list'" class="!mr-4">
          <el-button size="default" type="primary" @click="onHandleResetFields">
            <el-icon>
              <ele-Refresh/>
            </el-icon>
            重置
          </el-button>
        </el-form-item>
        <el-form-item v-auth="'user.list'" class="!mr-4">
          <el-button
              size="default"
              type="warning"
              @click="handleExport"
          >
            <el-icon>
              <ele-Download/>
            </el-icon>
            导出
          </el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="state.tableData.loading" :data="state.tableData.data" highlight-current-row
                style="width: 100%"
                @sort-change="handleSortChange">
        <el-table-column label="ID" prop="id" show-overflow-tooltip/>
        <el-table-column label="券名称" prop="couponName" show-overflow-tooltip/>
        <el-table-column label="券类型" prop="couponType">
          <template #default="scope">
            <dict-tag :options="coupon_type" :value="scope.row.couponType"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="消费金额" prop="consumptionAmount" sortable/>
        <el-table-column label="优惠金额" prop="discountAmount">
          <template #default="scope">
            {{
              scope.row.couponType === '4' ? scope.row.discountRatio + '%' : scope.row.discountAmount + '元'
            }}
          </template>
        </el-table-column>
        <!--        <el-table-column label="排序编码" prop="orderNumber" sortable/>-->
        <el-table-column label="开始时间" prop="startTime" show-overflow-tooltip sortable/>
        <el-table-column label="结束时间" prop="endTime" show-overflow-tooltip sortable/>
        <el-table-column label="备注" prop="remark"/>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button v-auth="'user.edit'" :disabled="scope.row.loginName === 'admin'" size="small" text
                       type="primary" @click="onOpenEditUser('edit', scope.row)">
              修改
            </el-button>
            <el-button v-auth="'user.del'" :disabled="scope.row.loginName === 'admin'" size="small" text
                       type="danger" @click="onRowDel(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="state.tableData.param.pageNum"
                     v-model:page-size="state.tableData.param.pageSize" :page-sizes="[10, 20, 30]" :pager-count="5"
                     :total="state.tableData.total" background class="mt15"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange">
      </el-pagination>
    </el-card>
    <shiftDialog ref="shiftDialogRef" @refresh="getTableData()"/>
  </div>
</template>

<script lang="ts" name="systemUser" setup>
import {defineAsyncComponent, getCurrentInstance, onMounted, reactive, ref} from 'vue';
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';
import {couponTemplateApi} from "/src/api/market/coupon/template";
import {dictDataApi} from "/@/api/sys/dictData";
import DictTag from "/@/components/DictTag/index.vue";
import {download} from "/@/utils/ruoyi";

// 引入组件
const shiftDialog = defineAsyncComponent(() => import('/@/views/market/coupon/template/dialog.vue'));

const {proxy} = getCurrentInstance();
const {coupon_type} = proxy.useDict("coupon_type");

// 定义变量内容
const shiftDialogRef = ref();
const queryFormRef = ref();
const state = reactive<any>({
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 10,
      sortName: 'orderNumber',
      sortOrder: 'asc',
      params: {
        couponName: '',
        couponType: ''
      },
    },
  },
  typeList: [],
});

const handleSortChange = (data: any) => {
  if (data.order) {
    if (data.order.indexOf('asc') > -1) {
      state.tableData.param.sortOrder = 'asc'
    } else {
      state.tableData.param.sortOrder = 'desc'
    }
    state.tableData.param.sortName = data.prop
  }
  getTableData();
};

// 初始化表格数据
const getTableData = () => {
  state.tableData.loading = true;
  couponTemplateApi()
      .getTableData(state.tableData.param)
      .then((res) => {
        state.tableData.data = res.data.records;
        state.tableData.total = res.data.total;
        state.tableData.loading = false;
      })
      .catch(() => {
        state.tableData.loading = false;
      });
};
// 打开新增用户弹窗
const onOpenAddUser = (type: string) => {
  shiftDialogRef.value.openDialog(type);
};
// 打开修改用户弹窗
const onOpenEditUser = (type: string, row: RowUserType) => {
  shiftDialogRef.value.openDialog(type, row);
};
// 删除用户
const onRowDel = (row: RowUserType) => {
  ElMessageBox.confirm(`此操作将永久删除账户“${row.userName}”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    couponTemplateApi()
        .delRecord(row)
        .then(() => {
          getTableData();
          ElMessage.success('删除成功');
        });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};
// 分页改变
const onHandleSizeChange = (val: number) => {
  state.tableData.param.pageSize = val;
  getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.tableData.param.pageNum = val;
  getTableData();
};
// 页面加载时
onMounted(() => {
  getTableData();

  // 券分类
  dictDataApi()
      .getDictByType("coupon_type")
      .then(res => {
        state.typeList = res.data;
      })
});
// 重置查询表单
const onHandleResetFields = () => {
  queryFormRef.value.resetFields();
  getTableData();
};

// 导出
const handleExport = () => {
  let downloadLoadingInstance = ElLoading.service({
    text: "正在导出数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  })
  couponTemplateApi()
      .exportRecord(state.tableData.param.params)
      .then(res => {
        download(res, '套餐卡信息.xlsx');
        downloadLoadingInstance.close();
      })
}
</script>
